
from model import ThoughtData
from typing import Optional
from loguru import logger


def log_thought(thought_data: ThoughtData) -> None:
    """Formats a ThoughtData object into a human-readable string for logging.

    Creates a multi-line log entry summarizing the key details of a thought,
    including its type (standard, revision, or branch), sequence number,
    content, and status flags.

    Args:
        thought_data: The ThoughtData object containing the thought details.

    Example format:
        Revision 5/10 (revising thought 3)
          Thought: Refined the analysis based on critique.
          Next Needed: True, Needs More: False
        Branch 6/10 (from thought 4, ID: alt-approach)
          Thought: Exploring an alternative approach.
          Branch Details: ID='alt-approach', originates from Thought #4
          Next Needed: True, Needs More: False
        Thought 1/5
          Thought: Initial plan for the analysis.
          Next Needed: True, Needs More: False
    """
    prefix: str
    context: str = ""
    branch_info_log: Optional[str] = None # Optional line for branch-specific details

    # Determine the type of thought and associated context
    if thought_data.isRevision and thought_data.revisesThought is not None:
        prefix = 'Revision'
        context = f' (revising thought {thought_data.revisesThought})'
    elif thought_data.branchFromThought is not None and thought_data.branchId is not None:
        prefix = 'Branch'
        context = f' (from thought {thought_data.branchFromThought}, ID: {thought_data.branchId})'
        # Prepare the extra detail line for branches
        branch_info_log = f"  Branch Details: ID='{thought_data.branchId}', originates from Thought #{thought_data.branchFromThought}"
    else:
        # Standard thought
        prefix = 'Thought'
        # No extra context needed for standard thoughts

    # Construct the header line (e.g., "Thought 1/5", "Revision 3/5 (revising thought 2)")
    header = f"{prefix} {thought_data.thoughtNumber}/{thought_data.totalThoughts}{context}"

    # Assemble the log entry lines
    log_lines = [
        header,
        f"  Thought: {thought_data.thought}" # Indent thought content
    ]
    if branch_info_log:
        log_lines.append(branch_info_log) # Add branch details if applicable

    # Add status flags line
    log_lines.append(f"  Next Needed: {thought_data.nextThoughtNeeded}, Needs More: {thought_data.needsMoreThoughts}")

    log_prefix = "--- Received Thought ---"
    if thought_data.isRevision:
        log_prefix = f"--- Received REVISION Thought (revising #{thought_data.revisesThought}) ---"
    elif thought_data.branchFromThought is not None:
        log_prefix = f"--- Received BRANCH Thought (from #{thought_data.branchFromThought}, ID: {thought_data.branchId}) ---"

    formatted_log_thought = "\n".join(log_lines)
    logger.info(f"\n{log_prefix}\n{formatted_log_thought}\n")
